from flask import Flask, request, send_file
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")

# 存储下载状态的字典
download_status = {}

@app.route("/download/<file_id>")
def download_file(file_id):
    """
    用户访问下载链接时触发
    """
    if file_id in download_status:
        # 通知本机下载已触发
        socketio.emit("download_triggered", {"file_id": file_id}, room=download_status[file_id])
        # 返回文件给用户
        return "file: {}".format(file_id), 200
        # return send_file("path/to/your/file.zip", as_attachment=True)
    return "File not found", 404

@socketio.on("connect")
def handle_connect():
    """
    本机连接时触发
    """
    file_id = request.args.get("file_id")
    if file_id:
        print(f"本机已连接，文件ID: {file_id}")
        download_status[file_id] = request.sid  # 保存连接会话 ID
    else:
        print("连接失败：缺少文件ID")

@socketio.on("disconnect")
def handle_disconnect():
    """
    本机断开连接时触发
    """
    file_id = request.args.get("file_id")
    if file_id in download_status:
        del download_status[file_id]
        print(f"本机已断开连接，文件ID: {file_id}")

if __name__ == "__main__":
    socketio.run(app, host="0.0.0.0", port=5000)